<template>
    <div id="p_timeauto" class="p_task">            
            <scroller v-model="pullStatus" lock-x scrollbar-y use-pullup :pullup-config="pullupConfig2" height="-97" ref="habitScrol" @on-pullup-loading="loadNext" :scroll-bottom-offset="200">
                <group class="group0">
                    <div v-if="actionArrComputed==0 && actionCurr.title != undefined" style="text-align:center;" ><img src="/static/z39h5/img/none.png" width="200" /></div>
                    <cell v-if="actionCurr.title == undefined" :title="appdown.title" :inline-desc="appdown.desc" @click.native="do2app">
                        <img slot="icon" :src="appdown.img">
                    </cell>

                    <swipeout>
                        <swipeout-item v-show="actionCurr.title != undefined" ref="actionCurr" @on-open="actionNew()" >
                            <div slot="left-menu">
                                <swipeout-button type="warn">新建动作</swipeout-button>
                            </div>
                            <div slot="content" class="vux-1px-t">                                         
                                <t-cell  :title="actionCurr.title" :tagTop="actionCurr" :value="actionCurr.duration" :inline-desc="actionCurr.start +'-'+(actionCurr.end?(actionCurr.end + ' '):'[now] ') + ' ' + actionCurr.addr">
                                    <img slot="icon" :src="actionCurr.img || '/static/z39h5/img/logo.png'">
                                </t-cell>
                            </div>
                        </swipeout-item>
                    </swipeout>

                    <swipeout>
                        <swipeout-item v-if="index<pageShowNum" @on-open="actionOpen(item, index,2)"  v-for="(item, index) in actionArrComputed" :key="index" ref="actionMove" >
                            <div slot="right-menu">
                                <swipeout-button @click.native="onDelClick('call',item,index)" type="warn">删除</swipeout-button>
                            </div>
                            <div slot="left-menu" v-if="item.key == undefined">
                                <swipeout-button type="warn">向上合并</swipeout-button>
                            </div>
                            <div slot="content" class="vux-1px-t">
                                <t-cell @click.native="onAction(item,index)" :title="item.title" :tagTop="item" :value="item.duration" :inline-desc="item.desc||(item.start +'-'+item.end + ' ' + item.addr)">
                                    <img slot="icon" :src="item.img || '/static/z39h5/img/logo.png'">
                                </t-cell>
                            </div>
                        </swipeout-item>
                    </swipeout>
                </group>

          </scroller>                
        
        <group>
           <popup-picker :show="showPopupPicker" @on-change="actionChange" :show-cell="false" title="TEST" :data="lifePickData" v-model="value5" @on-hide="showPopupPicker=false"></popup-picker>
         </group>
    </div>
</template>
<script>
import moment from "moment";

import api from '../../api';
import {
    mapState,
    mapActions
} from 'vuex'
let lifeFlagArr =[{name:"自定义",value:"custom",img:'logo'},
                {name:"醒",value:"wakeup",img:'wakeup'},
                {name:"起床",value:"getup",img:'getup'},
                {name:"洗漱1",value:"wash1",img:'wash'},
                {name:"洗澡",value:"bath",img:'bath'},
                {name:"厕所",value:"wc=10",img:'wc'},
                {name:"早饭",value:"breakfast",img:'eat'},
                {name:"录音",value:"tape",img:'record'},
                {name:"学习",value:"study",img:'study'},
                {name:"去上班",value:"gowork",img:'gowork'},
                {name:"上班",value:"workStart",img:'workStart'},
                {name:"工作准备",value:"workReady",img:'workReady'},
                {name:"腹肌撕裂者T4",value:"health",img:'health'},
                {name:"午饭",value:"lunch",img:'eat'},
                {name:"卡通",value:"cartoon",img:'cartoon'},
                {name:"晚饭",value:"dinner",img:'eat'},
                {name:"下班",value:"workEnd",img:'workEnd'},
                {name:"回家",value:"gohome",img:'gohome'},
                {name:"洗漱2",value:"wash2",img:'wash'},
                {name:"睡觉",value:"sleep",img:'sleep'}] ;

import TCell from "../t-cell/index.vue"

import {
    Tab,Cell,
    TabItem,
    TransferDomDirective as TransferDom,
    Toast,
    Swipeout,
    SwipeoutItem,
    SwipeoutButton,
    XButton,
    PopupPicker,
    Group,
    Picker,
    Box,
      XInput,
      XTextarea,Flexbox, FlexboxItem,Datetime,
    ButtonTab,    ButtonTabItem,  Scroller,
    Sticky
} from 'vux'

export default {
    directives: {
        TransferDom
    },
    components: {
        TCell,
        Tab,Cell,
        TabItem,
            Toast,
            Swipeout,
            SwipeoutItem,
            SwipeoutButton,
            XButton,
        PopupPicker,
        Group,
        Picker,
        Box,
          XInput,
          XTextarea,Flexbox, FlexboxItem,Datetime,
        ButtonTab,    ButtonTabItem,  Scroller,
        Sticky
    },
    computed: {
        actionArrComputed(){
            let today = moment().format("YYYY-MM-DD") ;
            var temp = this.actionArr.filter(function (action) {return action.typea==2 && action.timeday==today} ); 
            this.pageTotal = temp.length / this.pageNumOne ;
            if(this.pageTotal <= 1){
                setTimeout(() => {
                  this.$refs.habitScrol.disablePullup();
                }, 100)
            }else{
                setTimeout(() => {
                  this.$refs.habitScrol.enablePullup();
                }, 100)
            }
            this.$nextTick(() => {
                this.$refs.habitScrol.reset()
            })
            return temp;
        },
        ...mapState({
            uid: state => state.vux.uid,
            actionCurr: state => state.z39.actionCurr,
            actionArr: state => state.z39.actionArr,
            minDate: state => state.z39.minDate,
            maxDate: state => state.z39.maxDate,
            taskAll: state => state.z39.taskAll,
            tagDic: state => state.z39.tagDic,
            
            tagitems: state => state.z39.tagitems,
            tagitemDic: state => state.z39.tagitemDic
        })
    },
    watch: {
        "actionCurr": function() { 
            // console.log("actionCurr",this.actionCurr);
        },
        "actionArr": function() {
            if(!this.uid) return; //没登录就直接退出.不做提示,否则可能造成未登录用户的骚扰信息.
            var len = this.actionArr.length ;
            for(var i=len-1;i>= 0;i--){
                var item = this.actionArr[i] ;
                if( !item.id ){
                    this.taskAutoAdd(item);
                }
            }
            if( this.daySelect == moment().format("YYYY-MM-DD") ){
                this.actionDayArr = this.actionArr ;
            }
            // console.log("actionCurr");
        }
    },
    created() {        
        try{ if(isApp)runWatch() }catch(e){ console.log("app not ready") };
        
        this.showMonth = this.showMonth || moment().format("YYYY-MM");
        this.daySelect =  moment().format("YYYY-MM-DD");
    },
    filters: {  
        dayMin: function (month) {  
          return month.replace("-","")  
        }  ,
        dayOnly: function (day) {  
          var dayMon = moment(day) ;
          var value = dayMon.day();
          var todayStr = moment().format("YYYY-MM-DD");
          var dayDic = {1:"一",2:"二",3:"三",4:"四",5:"五",6:"六",0:"日"};
          var show = "" ;
          if( day == todayStr){
            show = "今";
          }else if(day < todayStr){
            show =  (value == 0 ||value ==6) ?dayDic[value] : dayMon.date() ;
          }else{
            show = dayMon.date() ;
          }
          return show ; 
        }
    }  ,
    mounted: function() {
        console.info("mount");
        if( this.uid == 0 )return ;
        this.taskautoGet({timeday:moment().format('YYYY-MM-DD')});
    },
    methods: {
        initPage(){
			if( this.uid == 0 )return ;
            if( !this.initHistory ){
                this.daysGet({type:2,month:this.showMonth}) ; 
                this.onDay(moment().format("YYYY-MM-DD")) ;
                this.initHistory = true ;
            }
        },
        getNameByKey(key){
            var temp = _.find(lifeFlagArr,function(item){ return item.value == key}) ;
            return temp.name ;
        },
        getItemByKey(key){
            var temp = _.find(lifeFlagArr,function(item){ return item.value == key}) ;
            return temp ;
        },
        check2merge(){
            var laskKey = "" ,tarAction,laskAction , laskActionStatic  ,del = false ;
            var lastActionKeyIndex ,laskActionKey ;
            var len = this.actionArrComputed.length ;
            for(var i=len-1;i>= 0 ;i--){  //从后往前合并
                var action = this.actionArrComputed[i] ;
                del = false ;                
                tarAction = laskAction ;
                if(tarAction && action.key && tarAction.key && tarAction.key == action.key ){
                    var start = tarAction.start < action.start ? tarAction.start : action.start ;
                    var end = tarAction.end > action.end ? tarAction.end : action.end ;
                    action.start = start ;
                    action.end = end ;
                    var dur = moment("2018-08-20 " + end ) - moment("2018-08-20 " + start ) ;
                    action.duration = (dur /1000).formatTime() ;
                        
                    // console.log("i",i , "del ", _.clone(action), 'change: ' , _.clone(tarAction) );
                    this.taskAutoPut( action ) ;
                    this.taskAutoDel( tarAction , i+i) ;
                    del = true ;
                }
                if( laskActionKey  && laskActionKey.key == action.key ){
                    this.autoChangeName( laskActionKey.title , action ,laskAction );
                }
                laskAction = action ;
                
                if( action.key ){
                    laskActionKey = action ;
                    lastActionKeyIndex = i ;
                }
            }
        },
        doMerge(index){
            var res = false ;
            var laskKey = "" ,tarAction,laskAction , laskActionStatic  ,del = false ;
            tarAction = this.actionArrComputed[index] ;
            if( index == 0){ //上面已经没有数据可合并;
                return res ;
            }
            for(var i=index-1;i>= 0 ;i--){
                var action = this.actionArrComputed[i] ;
                if( (action.typea == 2 && action.typea == tarAction.typea) || action.typea == 1){
                    if( action.title == tarAction.title ){
                        var start = tarAction.start < action.start ? tarAction.start : action.start ;
                        var end = tarAction.end > action.end ? tarAction.end : action.end ;
                        action.start = start ;
                        action.end = end ;
                        var dur = moment("2017-08-20 " + end ) - moment("2017-08-20 " + start ) ;
                        action.duration = (dur /1000).formatTime() ;
                        console.log( _.clone( tarAction),_.clone( action) );
                        this.taskAutoDel( tarAction, index) ;
                        this.taskAutoPut( action ) ;
                        res = true; 
                    }
                    break ;
                }
            }
            return res;
        },
        autoChangeName(name,startAction,endAction){
            var start = this.actionArr.indexOf(startAction) ;
            var end = this.actionArr.indexOf(endAction) ;
            // console.log("autoChangeName",name,start,end);
            var len = this.actionArr.length ;
            for(var i=start;i<= end ;i++){
                var action = this.actionArr[i] ;
                action.title = name ;
                this.taskAutoPut( action,false) ;
            }
        },
        onAction(item,index){
            this.showPopupPicker = true ;
            this.actionClick = item ;
            this.actionIndexClick = index ;
        },
        actionOpen(item,index,type){
            let dir = "" , target , arrIndex = index ;
            if(type == 1){
                target = this.$refs.actionStatic[index] ;
                dir = target.direction ;
                console.log("index",index,arrIndex);
            }else{
                target = this.$refs.actionMove[index] ;
                dir = target.direction ;
            }
            if( dir == "left"){
                let res = this.doMerge(index);
                if( res ){                    
                    this.$vux.toast.show({
                        text: "合并成功",
                        type: 'success'
                    })
                }else{                    
                    this.$vux.toast.show({
                        text: "上无同任务",
                        type: 'warn'
                    })
                }
                target.close();
            }            
            // console.log( _.clone(item) , index , dir );
        },
        actionNew(){
            try{
                actionNew(2,true); 
                this.$refs.actionCurr.close();
            }catch(e){
                console.error("moveListen.js miss actionNew");
            }
        },
        clickMerge(item,index){
            // 自动合并这里不需要.
        },        
        changeTime(){
            console.log("asdf");
            this.visibility = true ;
        },
        monthChange(val){            
            console.log("monthChange",val) ;
            this.daysGet({type:2,month:val}) ;            
        },
        daysGet(sdata){
            let _this = this;
            api.days(sdata).then(data => {
				if(data.errno !=0) return this.$vux.toast.show({text: data.errmsg ,type: 'warn'});
                
				data = data.data;
				_this.days = data ;                
            })
        },
        onDay(day){
            this.daySelect = day ;
            console.log("day",day);
            this.taskautoGet({timeday:day});
        },
        actionChange(val){
             val = val[0] ;
             console.log('val change', val) ;
             if( val == "custom"){

             }else{
                let item = this.getItemByKey(val);
                this.actionClick.key = val ;
                this.actionClick.name = item.name ;
                this.actionClick.title = this.actionClick.name ;
                this.actionClick.img = '/static/z39h5/img/'+ item.img +'.png' ;
                this.check2merge();
                if( this.actionClick ){
                    this.taskAutoPut(this.actionClick,true);                    
                }
                console.log( _.clone(this.actionClick));
             } 
        },
        handleEvents(type) {
            if (type == 'on-open') {
                this.swipeOpen = true;
            } else {
                this.swipeOpen = false;
            }
            console.log('event: ', type)
        },
        getData: function() {
            
        },
        taskautoGet:function(_data){
            api.taskautoGet(_data).then(data => {
				if(data == undefined) data={errmsg:"网络错误",errno:1001};
				if (data.errno != 0) return this.$vux.toast.show({text: data.errmsg ,type: 'warn'});
                
                data = data.data;     
                let acts = data.acts ;
                let day = _data.timeday ;
                this.$store.commit({type:"z39/actionSet",acts,day});
            })
        },
        taskAutoAdd:function(action){
            let _this = this;
            let _data = _.clone(action) ;
            api.taskautoAdd(_data).then(data => {
				if(data.errno !=0) return this.$vux.toast.show({text: data.errmsg ,type: 'warn'});
                
				data = data.data;     
				action.id = data ;
				try{
					appShake();
				}catch(e){console.warn("dcloud shake");}
                
            })
        },
        taskAutoPut:function(action,show){            
            let _this = this;
            let _data = _.clone(action) ;
            api.taskautoPut(_data).then(data => {
                if (data && data.errno == 0) {
                    data = data.data;
                    if(!show) return ;  // 不显示提示.
                    _this.$vux.toast.show({
                        text: "修改成功",
                        type: 'success'
                    })
                } else { //发生错误.
                    if(!show) return ;  // 不显示提示.
                    _this.$vux.toast.show({
                        text: data.errmsg,
                        type: 'warn'
                    })
                }
            })
        },
        taskAutoDel:function(action,index,show){            
            var tempIndex = this.actionArr.indexOf( action ) ;
            if( !action.id ){  //如果还未上传到服务器,本地则直接删除.
                this.actionArr.splice(tempIndex, 1) ;
                return ;
            }
            let _this = this;
            let _data = _.clone(action) ;
            api.taskautoDel({id:_data.id }).then(data => {
                if (data && data.errno == 0 && data.data > 0 ) {
                    data = data.data;           
                    this.actionArr.splice(tempIndex,1);                 
                    if(!show) return ;  // 不显示提示.
                    _this.$vux.toast.show({
                        text: "删除成功",
                        type: 'success'
                    })
                } else { //发生错误.
                    if(!show) return ;  // 不显示提示.
                    _this.$vux.toast.show({
                        text: data.errmsg,
                        type: 'warn'
                    })
                }
            })
        },
        loadNext(){
            if( this.pageIndex < this.pageTotal ){
                this.pageIndex ++ ;
                this.pageShowNum = this.pageIndex * this.pageNumOne ;
                // console.log("pageShowNum",this.pageShowNum) ;
                this.$refs.habitScrol.donePullup() ;
            }
			this.checkClosePullup();
        },
		checkClosePullup(){
            this.$refs.habitScrol.reset();
			if( this.pageIndex >= this.pageTotal){
				setTimeout(() => {
					this.$refs.habitScrol.disablePullup()
				}, 100)	
			}
		},
        readyReset(){ // @touchend="readyReset"
            return ; // 页面组件化,用router在使用时创建.这里就不需要这优化.
            if( this.resetId > 0){
                clearTimeout(this.resetId);
            }
            let _this = this ;
            this.resetId = setTimeout(() => {
                _this.pageIndex=1 ;
                _this.pageShowNum = _this.pageIndex * _this.pageNumOne ;
                _this.$nextTick(() => {
                    _this.$refs.habitScrol.reset({top: 0}) ;
                })
                _this.resetId = -1 ;
            },120000) //120000
        },
        do2app(){
            if(window.__wxjs_environment === 'miniprogram') return this.$vux.toast.show({text: "小程序中无法下载App" ,type: 'warn'});
            window.location.href = this.appdown.link ;
        },
        ...mapActions([
            
        ])
    },
    data() {
        return {
            resetId: -1,
            lifePickData:[lifeFlagArr],
            showPopupPicker: false,
            actionClick:{},
            actionIndexClick: 0 ,
            actCurr:{
                img: "/static/z39h5/img/logo.png",
                title: "还没数据",
                duration: "0",
                start: "开始",
                end: "结束"},
            appdown:{
                img: "/static/z39h5/img/down.jpg",
                title: "APP功能GPS",
                duration: "",
                desc: "点击下载,APP自动记录用户行为数据",
                link:"http://sj.qq.com/myapp/detail.htm?apkName=com.d7game.time"
            },
            actArr:[],
            actionLifeArr:[] ,
            actionDayArr:[] ,
            value5: ['custom'],
            timeindex: 1,
            weekEdit:false ,
            guideHeight: "500px",
            visibility: false ,
            showMonth:'',
            daySelect:"",
            days:[],
            initHistory:false ,
            pageIndex: 1 ,
            pageTotal: 2 ,
            pageShowNum:15,
            pageNumOne: 15 ,
              pullupConfig2: {
                content: '上拉加载更多',
                downContent: '松开进行加载',
                upContent: '上拉加载更多',
                loadingContent: '加载中...'
              },
            pullStatus: {
              pullupStatus: 'disabled'
            }
        }
    }
}

</script>
<style scoped>
#p_timeauto .vux-button-group{
    background-color: #fff; 
    padding-top: 1px;
}
#p_timeauto .timeBtn{width:70px;}
#p_timeauto .day {
    padding:2px 6px ;
    height: 32px;
}
#p_timeauto .day .vux-tab-item{
    background: #fff;
    line-height: 28px;    font-size: 16px;
}
#p_timeauto .day .vux-tab-selected {
    background: #eee;border-radius: 6px;
}

</style>
<style>
#p_timeauto .weui-search-bar:before {
    height: 0;
    border-top: 0;
}
#p_timeauto .day  .vux-tab-selected {
    background: #eee;
    border-radius: 4px;
}
</style>